package com.share.demo.controller;

import com.share.demo.event.WatcherA;
import com.share.demo.event.ZookeeperWatcher;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * author:caifan
 * date:2019/12/16
 */
@RestController
@RequestMapping("/rest/zookeeper")
public class ZookeeperRest {
    @Autowired
    private ZooKeeper zookeeper;

    @PostMapping("/create")
    public void create(@RequestParam("path")String path, @RequestParam("data")String data) throws Exception {
        WatcherA watcherA = new WatcherA(zookeeper, path);
        zookeeper.exists(path, watcherA);
        zookeeper.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    @GetMapping("/get")
    public String get(@RequestParam("path")String path) throws Exception {
        byte[] data = zookeeper.getData(path, new ZookeeperWatcher(), new Stat());
        if (null != data) {
            return new String(data);
        }
        return null;
    }

    @DeleteMapping("/delete")
    public void delete(@RequestParam String path) throws Exception {
        WatcherA watcherA = new WatcherA(zookeeper, path);
        zookeeper.exists(path, watcherA);
        zookeeper.delete(path, -1);
    }

}
